<?php
/*
 * @Description    : 
 * @Author         : QianLong
 * @Date           : 2023-04-24 10:44:35
 * @LastEditors    : QianLong
 * @Site           : http://www.21ds.cn
 * @LastEditTime   : 2024-05-15 17:34:29
 */

declare(strict_types=1);

namespace App\Amqp\Consumer;

use App\Common\RedisCache;
use App\Service\Common;
use Hyperf\Amqp\Result;
use Hyperf\Amqp\Annotation\Consumer;
use Hyperf\Amqp\Message\ConsumerMessage;
use PhpAmqpLib\Message\AMQPMessage;


#[Consumer(exchange: 'idp.push_log', routingKey: 'idp.push_log', queue: 'idp.push_log', name: "LogConsumer", nums: 1)]
class LogConsumer extends ConsumerMessage
{
    public function consumeMessage($data, AMQPMessage $message): string
    {
        if (!empty($data) && is_array($data)) {
            $redisCache = new RedisCache;
            $logData = $data['logData'];
            $logData['lsi_id'] = $data['lsi_id'];
            $logData['remote_ip'] = $data['param']['remote_ip'];
            $logData['remote_ip_area'] = (new Common)->ip2Region($data['param']['remote_ip']);
            $data['param']['remote_ip_area'] = $logData['remote_ip_area'];
            $logData['uid'] = (int)$data['serverInfo']['uid'];
            $logData['username'] = (int)$data['serverInfo']['username'];
            $logData['create_time'] = time();
            $logData['delete_time'] = time() + intval($data['serverInfo']['save_day']) * 86400;
            $logData['date'] = date('Y-m-d');
            $logData['only_hour'] = date('H') . ':00';
            $logData['_id'] = createULId();
            $logData['request_id'] = (isset($data['request_id']) && !empty($data['request_id'])) ? $data['request_id'] : $logData['_id'];
            // mongodb2()->site_log->insertOne($logData);
            $collection = mongodb2()->selectCollection('site_log');
            $collection->insertOne($logData);
            // 1=升序，-1=降序
            $hasIndex = $redisCache->getSetMongodbIndex('uid_create_req_lsiid');
            if (empty($hasIndex)) {
                $collection->createIndex(['uid' => 1, 'create_time' => -1, 'request_id' => -1, 'lsi_id' => -1], ['background' => true, 'name' => 'uid_create_req_lsiid']);
                $redisCache->getSetMongodbIndex('uid_create_req_lsiid_' . $logData['uid'], '1');
            }
            unset($logData, $collection);
            if (isset($data['serverInfo']['notice_open']) && $data['serverInfo']['notice_open'] == 1 && isset($data['serverInfo']['ps_id']) && !empty($data['serverInfo']['ps_id'])) {
                $pushServerInfo = $redisCache->getPushServer($data['serverInfo']['ps_id']);
                $ignoreThis = 0;
                if (isset($data['serverInfo']['notice_params_ignore']) && !empty($data['serverInfo']['notice_params_ignore'])) {
                    $browserParamsArr = explode("\n", $data['serverInfo']['notice_params_ignore']);
                    foreach ($browserParamsArr as $vo) {
                        $browserVoArray = explode('=', $vo);
                        if (count($browserVoArray) >= 2) {
                            if (isset($data['logData'][$browserVoArray[0]]) && strstr($data['logData'][$browserVoArray[0]], $browserVoArray[1]) != false && $ignoreThis == 0) {
                                $ignoreThis = 1;
                            }
                        }
                    }
                    unset($browserParamsArr, $browserVoArray, $vo);
                }
                if (!empty($pushServerInfo) && $ignoreThis == 0) {
                    $userSettingInfo = $redisCache->getUserSettingByUid($data['serverInfo']['uid']);
                    $pushData['dev_key'] = $userSettingInfo['dev_key'];
                    unset($userSettingInfo);
                    $pushData['ps_id'] = $data['serverInfo']['ps_id'];
                    $pushData['title'] = '【新日志提醒】- ' . $data['serverInfo']['title'];
                    $pushData['msg_type'] = 'markdown';
                    $pushData['atMobiles'] = $data['atMobiles'];
                    $contentNotice = '';
                    $markdownNotice = '';
                    if (isset($data['serverInfo']['notice_params']) && !empty($data['serverInfo']['notice_params'])) {
                        $noticeArray = explode('|', $data['serverInfo']['notice_params']);
                        if (!empty($noticeArray)) {
                            foreach ($noticeArray as $key) {
                                if (isset($data['param'][$key])) {
                                    $keyName = (isset($data['serverInfo']['fieldsName'][$key]) && !empty($data['serverInfo']['fieldsName'][$key])) ? $data['serverInfo']['fieldsName'][$key] : $key;
                                    if ($key == 'remote_ip') {
                                        $contentNotice .= '来源IP: ' . $data['param'][$key] . '(' . $data['param']['remote_ip_area'] . ')<br />';
                                        $markdownNotice .= " \n> **来源IP：**" . $data['param'][$key] . '(' . $data['param']['remote_ip_area'] . ')';
                                    } else {
                                        $contentNotice .= $keyName . ': ' . $data['param'][$key] . '<br />';
                                        $markdownNotice .= " \n> **{$keyName}：**" . $data['param'][$key];
                                    }
                                }
                            }
                        }
                    }
                    if (!empty($markdownNotice)) {
                        $markdownNotice .= "\n> \n> **[温馨提示]** 详情可 [前往企业开发者平台查看](http://console.21ds.cn/logs/ExceptionLog)";
                    }
                    $pushData['content'] = '【新日志提醒】- ' . $data['serverInfo']['title'] . '<br />' . $contentNotice . '请<a href="http://console.21ds.cn/logs/ExceptionLog">前往企业开发者平台查看</a>。';
                    $pushData['msg_content'] = "#### 【新日志提醒】- {$data['serverInfo']['title']} \n> **日志详情** \n> {$markdownNotice}";
                    (new Common)->doSendPush($pushData, $pushServerInfo['server_secret']);
                }
            }
            unset($pushServerInfo, $contentNotice, $markdownNotice);
        }
        unset($pushData);
        return Result::ACK;
    }
}
